import time

from django.db import transaction

from Robots.CodeForces import CodeForcesRobot
from Robots.HDU import HDURobot
from Robots.models import RobotAccount


class RobotFactory:
    @staticmethod
    def create_robot(robot_type, get_problem=True):
        robot_type_dict = {"CF": (CodeForcesRobot(), "CF"), "HDU": (HDURobot(), "HDU"), }
        if robot_type not in robot_type_dict:
            raise ValueError("不支持的机器人类型")

        if get_problem:
            return robot_type_dict[robot_type][0]

        robot, remote_oj_name = robot_type_dict[robot_type]
        available_account = None

        while not available_account:
            while not available_account:
                # 开启数据库事务
                with transaction.atomic():
                    # 使用 select_for_update() 获取行级锁
                    available_account = RobotAccount.objects.select_for_update().filter(
                        remote_oj__name=remote_oj_name,
                        is_active=True).first()

                    if not available_account:
                        time.sleep(1)
                    else:
                        # 将获取到的账号设置为不可用状态
                        available_account.is_active = False
                        available_account.save()
                print("正在尝试获取到可用账号")

        robot.set_account(token=available_account.token, username=available_account.username,
                          password=available_account.password)

        return robot
